package com.jiangjun.fetch.filter;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import javax.persistence.Id;

import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.bson.types.ObjectId;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.DOMReader;

import EDU.oswego.cs.dl.util.concurrent.FutureResult;

import com.jiangjun.fetch.FetchRss;
import com.jiangjun.fetch.common.WebContext;
import com.jiangjun.fetch.mongo.MongoDBSupport;
import com.jiangjun.fetch.threadpool.FetchHandleCallable;
import com.jiangjun.fetch.threadpool.FetchPicThreadPool;
import com.jiangjun.fetch.util.UUIDUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

public class ParseRssXmlFilter extends Filter {

	@Override
	public String doProcess(WebContext ctx) throws Exception {
		// TODO Auto-generated method stub
		MongoDBSupport mongoDBSupport = MongoDBSupport.getInstance();
		String lastUpdatetime = ctx.getLastUpdateTime();
		if (null != lastUpdatetime && !"".equals(lastUpdatetime)) {
			String id = ctx.getId();
			BasicDBObject param = new BasicDBObject();
			param.put("id", id);
			BasicDBObject data = new BasicDBObject();
			data.put("$set", new BasicDBObject("date", lastUpdatetime));
			mongoDBSupport.updateCollection(MongoDBSupport._FETCHRSS, param,
					data);
		}
		String collectionName = MongoDBSupport._FETCHPIC;
		String type = ctx.getType();
		if (type.equals("1")) {
			collectionName = MongoDBSupport._FETCHPIC;
			parseRssXml(ctx, collectionName);
		} else if (type.equals("2")) {
			collectionName = MongoDBSupport._FETCHTXT;
			parseRssXml(ctx, collectionName);
		} else if (type.equals("3")) {
			collectionName = MongoDBSupport._FETCHPICLIST;
			if(ctx.getUrl().indexOf("meitu.vvmini") > -1)
			{
				parseRssXml(ctx, collectionName);
			}else {
				parseRssXml4PicList(ctx, collectionName);
			}
			
		}
		return null;
	}
	
	public void parseRssXml4PicList(WebContext ctx,String collectionName) throws Exception{
		MongoDBSupport mongoDBSupport = MongoDBSupport.getInstance();
		// 解析Rss源XML
//		DOMReader dr = new DOMReader();
//		DOMParser parser = new DOMParser();
//		XMLInputSource xmlInputSource = new XMLInputSource(null, null, null,
//				new StringReader((String) ctx.getContent()), null);
//		try {
//			parser.parse(xmlInputSource);
//		} catch (XNIException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		org.w3c.dom.Document doc = parser.getDocument();
//		Document document = dr.read(doc);
		Document document = DocumentHelper.parseText((String) ctx.getContent());
		Element root = document.getRootElement();
		List<Element> urls = root.elements("url");
		for(Element item:urls)
		{
			String loc = item.elementText("loc");
			String title = item.elementText("title");
			String lastmod = item.elementText("lastmod");
			/**
			 * 判断数据库有没有这条数据
			 */
			BasicDBObject param = new BasicDBObject();
			param.put("url", loc);
			if (null == mongoDBSupport.queryOneByParam(collectionName, param,
					null)) {
				FetchRss fetchPicLis = new FetchRss();
				fetchPicLis.setTitle(title);
				fetchPicLis.setDes(title);
				fetchPicLis.setUrl(loc);
				fetchPicLis.setType(ctx.getType());// 是图片还是文字还是图片集合
				fetchPicLis.setParent_id(ctx.getId());
				fetchPicLis.setParent_name(ctx.getDes());
				fetchPicLis.setXpath(ctx.getXpath());
				fetchPicLis.setDate(lastmod);
				fetchPicLis.setId(UUIDUtil.getUUID());
				FetchPicThreadPool.execute(new FutureResult()
						.setter(new FetchHandleCallable(fetchPicLis)));
			}
		}
	}

	public void parseRssXml(WebContext ctx, String collectionName) throws Exception{
		MongoDBSupport mongoDBSupport = MongoDBSupport.getInstance();
		// 解析Rss源XML
//		DOMReader dr = new DOMReader();
//		DOMParser parser = new DOMParser();
//		System.out.println((String) ctx.getContent());
//		XMLInputSource xmlInputSource = new XMLInputSource(null, null, null,
//				new StringReader((String) ctx.getContent()), null);
//		try {
//			parser.parse(xmlInputSource);
//		} catch (XNIException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		org.w3c.dom.Document doc = parser.getDocument();
//		Document document = dr.read(doc);
		System.out.println((String) ctx.getContent());
		Document document = null;
		try {
			document = DocumentHelper.parseText((String) ctx.getContent());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		Element root = document.getRootElement();
		Element channel = root.element("channel");
		List<Element> items = channel.elements("item");
		for (Element item : items) {
			String title = item.elementText("title");
			String link = item.elementText("link");
			String description = item.elementText("description");
			String pubDate = item.elementText("pubDate");
//			String category = item.elementText("category");

			/**
			 * 判断数据库有没有这条数据
			 */
			BasicDBObject param = new BasicDBObject();
			param.put("url", link);
			if (null == mongoDBSupport.queryOneByParam(collectionName, param,
					null)) {
				FetchRss fetchPic = new FetchRss();
				fetchPic.setTitle(title);
				fetchPic.setDes(description);
				fetchPic.setUrl(link);
				fetchPic.setType(ctx.getType());// 是图片集还是文字集合
				fetchPic.setParent_id(ctx.getId());
				fetchPic.setParent_name(ctx.getDes());
				fetchPic.setXpath(ctx.getXpath());
				fetchPic.setDate(pubDate);
				fetchPic.setId(UUIDUtil.getUUID());
				FetchPicThreadPool.execute(new FutureResult()
						.setter(new FetchHandleCallable(fetchPic)));
			}
		}
	}
}
